package cc.booku.owlbox.UserSettingsPage;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.timmy.tdialog.TDialog;
import com.timmy.tdialog.base.BindViewHolder;
import com.timmy.tdialog.listener.OnBindViewListener;
import com.timmy.tdialog.listener.OnViewClickListener;

import java.io.File;
import java.io.IOException;
import java.util.List;

import cc.booku.owlbox.AppUpdate.DownloadService;
import cc.booku.owlbox.AppUpdate.app_version_class;
import cc.booku.owlbox.ArtDesign.SystemUtil;
import cc.booku.owlbox.FileOperations.FileoOperations;
import cc.booku.owlbox.R;
import cc.booku.owlbox.RsaUtil.Decrypt;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;

import static cc.booku.owlbox.FileOperations.FileoOperations.fileIsExists;


public class ExplainActivity extends AppCompatActivity {
    private WebView webView;
    //private String url = "file:////android_asset/bootstrap/about.html";
    private String interlinkage = "";
    private Toolbar Toolbar;
    MyReceiver receiver = new MyReceiver();
    private String ProfilePath = "/storage/emulated/0/OwlDatabase/Profile.txt";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.layout_explain);
        //初始化工具栏
        LoadToolbar();


        //状态栏颜色
        SystemUtil.setStatusBarColor(this, Color.parseColor("#448aca"));
        //给页面加上返回按钮https://blog.csdn.net/ssgue/article/details/83104552
//        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
//        if(actionBar != nulldata){
//            actionBar.setHomeButtonEnabled(true);
//            actionBar.setDisplayHomeAsUpEnabled(true);
//        }

        //新页面接收数据
        Bundle bundle = this.getIntent().getExtras();
        //接收name值
        interlinkage = bundle.getString("interlinkage");
        Log.i("获取到的interlinkage值为", interlinkage);

        webView = (WebView) findViewById(R.id.webView);
        //webView.loadUrl(url);
        //webView.loadUrl("file:///android_asset/bootstrap-3.3.7-dist/about.html");
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
/*
        Bundle bundle=getIntent().getExtras();
        int id=bundle.getInt("photo");
        String message=bundle.getString("message");
        ImageView Iv=(ImageView) findViewById(R.id.Iv);
        Iv.setImageResource(id);
        TextView tv=(TextView) findViewById(R.id.tv_message);
        tv.setText(message);
*/
        initWebView();
    }

    private void LoadToolbar() {
        Toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(Toolbar);//利用Toolbar代替ActionBar
        //Toolbar.inflateMenu(R.menu.menu_user);
        //设置的点击事件
        Toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到用户设置页面
                finish();
            }
        });
        //添加menu 菜单点击事件
        Toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.action_update:
                        //动态申请权限
                        requestPermission();
                        //注册广播
                        regist();
                        //得到程序最新版本地址

                        String ProfileStr = FileoOperations.readFromSDFile(ExplainActivity.this, ProfilePath);
                        //读取配置文件信息
                        try {
                            JSONObject obj = JSONObject.parseObject(ProfileStr);
                            String result = obj.getString("软件更新地址");
                            String ciphertext = obj.getString("地址密文");
                            String res = Decrypt.RsaDecrypt(ExplainActivity.this, ciphertext);
                            AppVersion(res + result);

                        } catch (Exception e) {

                            Toast.makeText(ExplainActivity.this, "更新地址解析错误", Toast.LENGTH_SHORT).show();
//异常处理
                        }


                        break;

                }
                return true;
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreatePanelMenu(int featureId, Menu menu) {
        getMenuInflater().inflate(R.menu.menu_update, menu);//toolbar添加menu菜单
        return true;
    }

//********************************程序更新******************************
    //动态申请权限

    //动态申请权限
    private void requestPermission() {
        if (ContextCompat.checkSelfPermission(ExplainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(ExplainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }
    }

    //注册广播
    private void regist() {
        IntentFilter intentFilter = new IntentFilter(DownloadService.BROADCAST_ACTION);
        intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
        LocalBroadcastManager.getInstance(this).registerReceiver(receiver, intentFilter);
    }


    public class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "app-release.apk");
            //获取权限
            try {
                Runtime.getRuntime().exec("chmod 777" + file.getCanonicalPath());
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 由于没有在Activity环境下启动Activity,设置下面的标签
            intent = new Intent(Intent.ACTION_VIEW);
            //如果设置，这个活动将成为这个历史堆栈上的新任务的开始
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //判读版本是否在7.0以上
            if (Build.VERSION.SDK_INT >= 24) {
                //7.0以上的版本
                Uri apkUri = FileProvider.getUriForFile(context, "cc.booku.owlbox.FileProvider", file);
                //添加这一句表示对目标应用临时授权该Uri所代表的文件
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            } else {
                //7.0以下的版本
                intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            }
            startActivity(intent);
        }
    }


    private void AppVersion(String url) {


        OkHttpClient client = new OkHttpClient();
        Request request = new Request
                .Builder()
                .url(url)//要访问的链接
                .build();

        Call call = client.newCall(request);
        call.enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                String res = response.body().string();
                //Log.i("response===========>",res);

                try {
                    initUpdate(res);
                } catch (Exception e) {

                    Log.i("response===========>", res);
//异常处理
                }

            }
        });

    }


    private void initUpdate(String json) {


        //http://www.shuchuwenku.vip/MavBox/statistics/version.php
        List<app_version_class> list = JSON.parseArray(json, app_version_class.class);

        for (int i = 0; i < list.size(); i++) {
            String version = list.get(i).getVersion();
            String title = list.get(i).getTitle();
            String time = list.get(i).getTime();
            String content = list.get(i).getContent();
            String down_url = list.get(i).getDown_url();
            Log.i("response===========>", version + title + time + content + down_url);
            if (pm(list.get(i).getVersion())) {

                Tupdate(down_url, title, version, content);

            }


        }


    }

    private void Tupdate(final String down_url, final String title, final String filename, final String content) {


        if (fileIsExists("/storage/emulated/0/Download/app-release.apk")) {
            deleteSingleFile("/storage/emulated/0/Download/app-release.apk");
        }


        new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.tdialog_version_upgrde)
                .setScreenWidthAspect(this, 0.9f)
                .addOnClickListener(R.id.tv_cancel, R.id.tv_confirm)

                .setOnBindViewListener(new OnBindViewListener() {
                    public void bindView(BindViewHolder viewHolder) {
                        viewHolder.setText(R.id.tv_upgrade_content, content);
                    }
                })
                .setOnViewClickListener(new OnViewClickListener() {


                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {
                        switch (view.getId()) {
                            case R.id.tv_cancel:
                                tDialog.dismiss();
                                break;
                            case R.id.tv_confirm:

                                Toast.makeText(ExplainActivity.this, "如果没有弹出安装界面,请手动安装", Toast.LENGTH_SHORT).show();
                                Intent serviceIntent = new Intent(ExplainActivity.this, DownloadService.class);
                                serviceIntent.setData(Uri.parse(down_url));
                                startService(serviceIntent);


                                tDialog.dismiss();
                                break;
                        }
                    }
                })
                .create()
                .show();

    }


    private boolean deleteSingleFile(String filePath$Name) {
        File file = new File(filePath$Name);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                Log.e("--Method--", "Copy_Delete.deleteSingleFile: 删除单个文件" + filePath$Name + "成功！");
                return true;
            } else {
                Toast.makeText(getApplicationContext(), "删除单个文件" + filePath$Name + "失败！", Toast.LENGTH_SHORT).show();
                return false;
            }
        } else {
            Toast.makeText(getApplicationContext(), "删除单个文件失败：" + filePath$Name + "不存在！", Toast.LENGTH_SHORT).show();
            return false;
        }
    }

    private boolean pm(String versioncode) {

        //获取包管理者对象
        PackageManager pm = getPackageManager();

        PackageInfo info = null;
        try {
            info = pm.getPackageInfo(getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        //获取版本号和版本名称


        if (versioncode.equals(info.versionName)) {
            return false;
        } else return true;


    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
    }


//    /**
//     * @param file
//     * @return
//     * @Description 安装apk
//     */
//    protected void installApk(File file) {
//        Intent intent = new Intent(Intent.ACTION_VIEW);
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // 7.0+以上版本
//            Uri apkUri = FileProvider.getUriForFile(this, "com.shawpoo.app.fileprovider", file);  //包名.fileprovider
//            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
//        } else {
//            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
//        }
//        this.startActivity(intent);
//    }


    //*********************************************************************************************************************

    private void initWebView() {
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //系统默认会打开系统浏览器去打开网页，为了要显示在自己的webview中必须设置这个属性
                view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }
            //加载开始时调用

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                if (null == view) {
                    view.loadUrl(interlinkage);
                }
                super.onPageStarted(view, url, favicon);

            }
            // 加载结束时调用

            @Override
            public void onPageFinished(WebView view, String url) {

                super.onPageFinished(view, url);

            }

            private boolean isSuccess = false;
            private boolean isError = false;

            //加载错误的时候会回调，在其中可做错误处理，比如再请求加载一次，或者提示404的错误页面
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                if (!isError) {
                    isSuccess = true;
                    webView.loadUrl(interlinkage);
                    //回调成功后的相关操作
                }
                isError = false;
                webView.loadUrl("file:////android_asset/app_updatainfo.html");
            }

            //当接收到https错误时，会回调此函数，在其中可以做错误处理
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                webView.loadUrl("file:////android_asset/app_updatainfo.html");
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                url = url.toLowerCase();
                if (!url.contains(url)) {
                    if (!ADFilterTool.hasAd(ExplainActivity.this, url)) {
                        return super.shouldInterceptRequest(view, url);
                    } else {
                        return new WebResourceResponse(null, null, null);
                    }
                } else {
                    return super.shouldInterceptRequest(view, url);
                }
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {
            //加载进度
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                Log.e("WebView>>>>>>>", newProgress + "");
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onRequestFocus(WebView view) {
                super.onRequestFocus(view);
            }

            @Override
            public void onCloseWindow(WebView window) {
                super.onCloseWindow(window);
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
                return super.onJsConfirm(view, url, message, result);
            }

        });

        webView.loadUrl(interlinkage);
        // 得到setting
        WebSettings webSettings = webView.getSettings();
        //设置支持Javascript
        webSettings.setJavaScriptEnabled(true);
        //支持的语言类型
        webSettings.setDefaultTextEncodingName("UTF-8");
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);

        webSettings.setDomStorageEnabled(true);


//关键代码
        webView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
                if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        //这里处理返回键事件
                        if (webView.canGoBack()) {
                            webView.goBack();
                            //Toast.makeText(getActivity(), "ok", Toast.LENGTH_SHORT).show();
                            return true;
                        }
                    }
                }
                return false;
            }
        });
    }
}

class ADFilterTool {
    public static boolean hasAd(Context context, String url) {
        Resources res = context.getResources();
        String[] adUrls = res.getStringArray(R.array.adBlockUrl);
        for (String adUrl : adUrls) {
            if (url.contains(adUrl)) {
                return true;
            }
        }
        return false;
    }
}
